package com.ruoyi.web.controller.member;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.GuaMethodEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.yijing.domain.*;
import com.ruoyi.yijing.service.*;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import software.amazon.awssdk.services.s3.endpoints.internal.Value;

import java.util.*;

@RestController
@RequestMapping("/member/")
public class MemberController extends Base {

    @Autowired
    private ICustomerInfoAccountService customerInfoAccountService;

    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    private IYjCategoryService categoryService;

    @Autowired
    private IYjReferencesService referencesService;

    @Autowired
    private IYjBookService bookService;

    @Autowired
    private IYjBookChapterService chapterService;

    @Autowired
    private IYjDaShangService daShangService;

    @Autowired
    private IYjCustomerGuaiService customerGuaService;

    @Autowired
    private IYjGuaiYaoService guaYaoService;

    @Autowired
    private IYjGuaiService guaService;

    @Autowired
    private IYjGuaiFamousService guaFamousService;

    @Autowired
    private IYjYuYueService yuYueService;

    @Autowired
    private IYjGuaiCategoryService guaCategoryService;


    /**
     * 开始卜卦
     * @param gua
     * @return
     */
    @PostMapping(value = "startGua")
    public AjaxResult startGua(@RequestBody YjCustomerGua gua){
        String appId = getAppId();
        CustomerInfo customerInfo = getMemberInfo();
        if (StringUtils.isEmpty(appId)){
            return AjaxResult.error("缺少AppId参数");
        }
        if (customerInfo == null){
            return AjaxResult.error("请先登陆再卜卦");
        }
        if (gua.getCategoryId() == null){
            return AjaxResult.error("请先选择占卜问题");
        }
        if (StringUtils.isEmpty(gua.getGuaMethod())){
            return AjaxResult.error("缺少卜卦方法");
        }
        YjCategory cate = categoryService.selectYjCategoryById(gua.getCategoryId());
        YjCustomerGua data = new YjCustomerGua();
        data.setCategoryId(gua.getCategoryId());
        if (cate != null){
            data.setCategoryName(cate.getName());
        }
        data.setCustomerId(customerInfo.getCustomerUid());
        data.setCreateBy(customerInfo.getCustomerName());
        data.setGuaMethod(GuaMethodEnum.getNameByKey(gua.getGuaMethod()));
        data.setCreateTime(new Date());
        data.setAppId(appId);
        data.setPhone(customerInfo.getPhone());
        data.setXiangStatus("0");
        data.setFateStatus("0");
        data.setHeadImage(customerInfo.getHeadImage());
        customerGuaService.insertYjCustomerGuai(data);
        data.setGuaMethod(gua.getGuaMethod());
        return AjaxResult.success(data);
    }

    /**
     * 完成摇卦
     * @param gua
     * @return
     */
    @PostMapping(value = "finishGua")
    public AjaxResult finishGua(@RequestBody YjCustomerGua gua){
        if (gua.getId() == null){
            return AjaxResult.error("缺少卜卦ID");
        }
        YjCustomerGua data = customerGuaService.selectYjCustomerGuaiById(gua.getId());
        if (data == null){
            return AjaxResult.error("没有找到卜卦资料");
        }
        if (data.getGuaId() != null){
            return AjaxResult.success(data);
        }
        if (gua.getYao1() == null || gua.getYao2() == null || gua.getYao3() == null || gua.getYao4() == null || gua.getYao5() == null || gua.getYao6() == null){
            return AjaxResult.error("需获得6爻才能完成推演");
        }
        data.setYao1(gua.getYao1());
        data.setYao2(gua.getYao2());
        data.setYao3(gua.getYao3());
        data.setYao4(gua.getYao4());
        data.setYao5(gua.getYao5());
        data.setYao6(gua.getYao6());

        GuaVo guaVo = new GuaVo();
        if (data.getYao1()%2>0){
            guaVo.setYao1("1");
        }else{
            guaVo.setYao1("0");
        }
        if (data.getYao2()%2>0){
            guaVo.setYao2("1");
        }else{
            guaVo.setYao2("0");
        }
        if (data.getYao3()%2>0){
            guaVo.setYao3("1");
        }else{
            guaVo.setYao3("0");
        }
        if (data.getYao4()%2>0){
            guaVo.setYao4("1");
        }else{
            guaVo.setYao4("0");
        }
        if (data.getYao5()%2>0){
            guaVo.setYao5("1");
        }else{
            guaVo.setYao5("0");
        }
        if (data.getYao6()%2>0){
            guaVo.setYao6("1");
        }else{
            guaVo.setYao6("0");
        }

        guaVo = guaYaoService.selectYjGuaiYao(guaVo);
        if (guaVo == null){
            return AjaxResult.error("没有找到卦的信息");
        }
        data.setGuaId(guaVo.getGuaId());
        //data.setJiXiong();
        data.setQingXiang(gua.getQingXiang());
        if (StringUtils.isNotEmpty(data.getQingXiang())) {
            data.setXiangStatus("1");
        }
        data.setShangId(gua.getShangId());
        data.setShangName(gua.getShangName());
        if (data.getShangId() != null) {
            data.setFateStatus("1");
        }
        data.setFinishTime(new Date());
        YjGua guaInfo = guaService.selectYjGuaiByGuaiId(data.getGuaId());
        YjGuaCategory query = new YjGuaCategory();
        query.setGuaId(data.getGuaId());
        query.setCategoryId(data.getCategoryId().intValue());
        List<YjGuaCategory> list = guaCategoryService.selectYjGuaiCategoryList(query);
        if (list.size()>0){
            data.setJiXiong(list.get(0).getJiXiong());
            data.setResult(list.get(0).getRelation());
        }else{
            data.setJiXiong(guaInfo.getJiXiong());
            data.setResult(guaInfo.getRemark());
        }
        data.setGuaInfo(guaInfo);
        data.setRemark(getJieGuaRemark(data,guaVo));
        customerGuaService.updateYjCustomerGuai(data);
        return AjaxResult.success(customerGuaService.selectYjCustomerGuaiById(gua.getId()));
    }

    /**
     * 解卦的基本原则
     1、没有变爻：在《易经》中查出本卦的卦辞,根据这个卦词的意思来解释。
     2、一个变爻：在《易经》中查出本卦的变爻的爻辞，根据这个爻词的意思来解释。
     3、二个变爻：在《易经》中查出本卦的两个变爻的爻辞,根据这两个爻的爻词的意思来解释,但是要以上爻的爻词为主。
     4、三个变爻：在《易经》中分别查出本卦和变卦的卦辞，以本卦的卦词为主，变卦的卦词为辅，综合解释。
     5、卦中有四个变爻，用变卦的两个不变爻的爻辞解卦。
     6、五个变爻：在《易经》中查出这个本卦的变卦，然后用变卦中不变的那个爻的爻词来解释。
     7、六爻皆变：在《易经》中查出这个本卦的变卦,根据这个变卦卦词的意思来解释，如果是乾坤两卦就用“用九”、“用六”解卦，其他则用变卦的卦辞解卦。
     * @param data
     * @return
     */
    private String getJieGuaRemark(YjCustomerGua data,GuaVo guaVo){
        String rst = new String();
        List<Integer> map = new ArrayList<>();
        if (data.getYao1() == 6 || data.getYao1() == 9){
            map.add(1);
        }
        if (data.getYao2() == 6 || data.getYao2() == 9){
            map.add(2);
        }
        if (data.getYao3() == 6 || data.getYao3() == 9){
            map.add(3);
        }
        if (data.getYao4() == 6 || data.getYao4() == 9){
            map.add(4);
        }
        if (data.getYao5() == 6 || data.getYao5() == 9){
            map.add(5);
        }
        if (data.getYao6() == 6 || data.getYao6() == 9){
            map.add(6);
        }
        List<YjGuaYao> yaoList = data.getGuaInfo().getYaoList();
        if (map.size()==0){
            rst = "本次推演没有出现变爻，故使用该卦的卦象哲理解析：\n"+data.getGuaInfo().getRemark();
        }else if (map.size()==1){
            rst = "本次推演第"+map.get(0)+"爻出现了变爻，故使用该爻的爻辞哲理解析：\n"+yaoList.get(map.get(0)-1).getRemark();
        }else if (map.size()==2){
            int yao1 = map.get(0);
            int yao2 = map.get(1);
            if (yao1>yao2){
                rst = "本次推演第"+yao1+"、"+yao2+"爻出现变爻，以第"+yao1+"爻爻辞哲理为主要参考：\n";
                rst +=  yaoList.get(yao1-1).getRemark();
                rst += "\n";
                rst += "以第"+yao2+"爻爻辞哲理为次要参考：\n";
                rst += yaoList.get(yao2-1).getRemark();
            }else{
                rst = "本次推演第"+yao2+"、"+yao1+"爻出现变爻，以第"+yao2+"爻爻辞哲理为主要参考：\n";
                rst +=  yaoList.get(yao2-1).getRemark();
                rst += "\n";
                rst += "以第"+yao1+"爻爻辞哲理为次要参考：\n";
                rst += yaoList.get(yao1-1).getRemark();
            }
        }else{

                    if (guaVo.getYao1().equals("0")){
                        guaVo.setYao1("1");
                    }else{
                        guaVo.setYao1("0");
                    }

                    if (guaVo.getYao2().equals("0")){
                        guaVo.setYao2("1");
                    }else{
                        guaVo.setYao2("0");
                    }

                    if (guaVo.getYao3().equals("0")){
                        guaVo.setYao3("1");
                    }else{
                        guaVo.setYao3("0");
                    }

                    if (guaVo.getYao4().equals("0")){
                        guaVo.setYao4("1");
                    }else{
                        guaVo.setYao4("0");
                    }

                    if (guaVo.getYao5().equals("0")){
                        guaVo.setYao5("1");
                    }else{
                        guaVo.setYao5("0");
                    }

                    if (guaVo.getYao6().equals("0")){
                        guaVo.setYao6("1");
                    }else{
                        guaVo.setYao6("0");
                    }

            guaVo = guaYaoService.selectYjGuaiYao(guaVo);
            YjGua cuoGua = guaService.selectYjGuaiByGuaiId(guaVo.getGuaId());
            if (map.size()==3){
                rst = "本次推演有3爻出现变卦，以本卦卦象哲理为主要参考：\n";
                rst +=  data.getGuaInfo().getRemark();
                if (guaVo != null){
                    if (cuoGua != null){
                        rst += "\n";
                        rst += "以以错卦【"+cuoGua.getName()+"】卦象哲理作为次要参考：\n";
                        rst += cuoGua.getRemark();
                    }
                }
            }else if (map.size()==4){
                List<Integer> source = new ArrayList<>();
                source.add(1);
                source.add(2);
                source.add(3);
                source.add(4);
                source.add(5);
                source.add(6);
                List<Integer> list = subYao(map,source);
                int yao1 = list.get(0);
                int yao2 = list.get(1);
                yaoList = cuoGua.getYaoList();
                if (yao1>yao2){
                    rst = "本次推演有4爻出现变爻，采用错卦【"+cuoGua.getName()+"】卦不变的爻作为分析。\n";
                    rst += "以第"+yao1+"爻作为主要参考：\n";
                    rst +=  yaoList.get(yao1-1).getRemark();
                    rst += "\n";
                    rst += "以第"+yao2+"爻作为次要参考：";
                    rst += "\n";
                    rst += yaoList.get(yao2-1).getRemark();
                }else{
                    rst = "本次推演有4爻出现变爻，采用错卦【"+cuoGua.getName()+"】卦不变的爻作为分析。\n";
                    rst += "以第"+yao2+"爻作为主要参考：\n";
                    rst +=  yaoList.get(yao2-1).getRemark();
                    rst += "\n";
                    rst += "以第"+yao1+"爻作为次要参考：";
                    rst += "\n";
                    rst += yaoList.get(yao1-1).getRemark();
                }
            }else if (map.size() == 5){
                List<Integer> source = new ArrayList<>();
                source.add(1);
                source.add(2);
                source.add(3);
                source.add(4);
                source.add(5);
                source.add(6);
                List<Integer> list = subYao(map,source);
                yaoList = cuoGua.getYaoList();
                rst = "本次推演有5爻出现变爻，故采用本卦对应的错卦不变的爻的爻辞哲理解析。"+yaoList.get(list.get(0)-1).getRemark();
            }else if (map.size() == 6){
                rst = "本次推演6爻全都出现变爻，故采用本卦对应的错卦的卦象哲理解析。"+cuoGua.getRemark();
            }
        }
        return rst;
    }

    private List<Integer> subYao(List<Integer> yao, List<Integer> source){
        source.removeAll(yao);
        return source;
    }

    /**
     * 卜卦打赏
     * @param gua
     * @return
     */
    @PostMapping(value = "dashang")
    public AjaxResult dashang(@RequestBody YjCustomerGua gua){
        if (gua.getId() == null){
            return AjaxResult.error("缺少卜卦ID");
        }
        if (gua.getShangId() == null){
            return AjaxResult.error("缺少礼物ID");
        }
        if (StringUtils.isEmpty(gua.getShangName())){
            return AjaxResult.error("缺少礼物名称");
        }
        YjCustomerGua data = customerGuaService.selectYjCustomerGuaiById(gua.getId());
        if (data == null){
            return AjaxResult.error("没有找到卜卦资料");
        }
        data.setShangId(gua.getShangId());
        data.setShangName(gua.getShangName());
        data.setFateStatus("1");
        customerGuaService.updateYjCustomerGuai(data);
        return AjaxResult.success("感谢打赏！");
    }

    /**
     * 查询卦的详情
     * @param id
     * @return
     */
    @GetMapping(value = "getCustomerGua/{id}")
    public AjaxResult getCustomerGua(@PathVariable(value = "id", required = true) Long id) {
        YjCustomerGua gua = customerGuaService.selectYjCustomerGuaiById(id);
        YjGua guaInfo = guaService.selectYjGuaiByGuaiId(gua.getGuaId());
        if (guaInfo != null){
            gua.setGuaInfo(guaInfo);
            YjGuaFamous fQuery = new YjGuaFamous();
            fQuery.setGuaId(gua.getGuaId());
            guaInfo.setFamousList(guaFamousService.selectYjGuaiFamousList(fQuery));
        }
        return AjaxResult.success(gua);
    }

    /**
     * 查询我的卜卦
     * @return
     */
    @GetMapping(value = "getMyGuaList")
    public AjaxResult getMyGua() {
        CustomerInfo ci =  getMemberInfo();
        if (ci == null){
            return AjaxResult.success(new ArrayList<>());
        }
        YjCustomerGua query = new YjCustomerGua();
        query.setCustomerId(ci.getCustomerUid());
        List<YjCustomerGua> list = customerGuaService.selectYjCustomerGuaiList(query);
        return AjaxResult.success(list);
    }

    /**
     * 预约解卦，查看全景运势
     * @param yuyue
     * @return
     */
    @PostMapping(value = "yuyue")
    public AjaxResult yuyue(@RequestBody YjYuYue yuyue){
        CustomerInfo ci =  getMemberInfo();
        if (ci == null){
            return AjaxResult.error("请先登陆再预约");
        }
        if (yuyue.getCustomerGuaId() == null){
            return AjaxResult.error("缺少卜卦ID");
        }
        if (StringUtils.isEmpty(yuyue.getFirstName())){
            return AjaxResult.error("姓氏不能为空");
        }
        if (StringUtils.isEmpty(yuyue.getSex())){
            return AjaxResult.error("性别不能为空");
        }
        if (StringUtils.isEmpty(yuyue.getPhone())){
            return AjaxResult.error("电话不能为空");
        }
        yuyue.setCreateTime(new Date());
        yuyue.setProcessStatus("0");
        yuyue.setPayStatus("0");
        yuyue.setCustomerId(ci.getCustomerUid());
        yuyue.setCreateBy(ci.getCustomerName());
        yuYueService.insertYjYuYue(yuyue);
        return AjaxResult.success("预约成功！");
    }

    /**
     * 查询64卦列表
     * @return
     */
    @GetMapping(value = "get64Gua")
    public AjaxResult get64Gua() {
        return AjaxResult.success(guaService.selectGuaList());
    }

    /**
     * 查询64卦详情
     * @return
     */
    @GetMapping(value = "getGua/{guaId}")
    public AjaxResult getGua(@PathVariable(value = "guaId", required = true) Integer guaId) {
        YjGua gua = guaService.selectYjGuaiByGuaiId(guaId);
        if (gua != null) {
            YjGuaFamous fQuery = new YjGuaFamous();
            fQuery.setGuaId(gua.getGuaId());
            gua.setFamousList(guaFamousService.selectYjGuaiFamousList(fQuery));
        }
        return AjaxResult.success(gua);
    }

    /**
     * 获取占卜的问题
     * @return
     */
    @GetMapping(value = "getCategory")
    public AjaxResult getCategory() {
        YjCategory query = new YjCategory();
        query.setDataStatus("1");
        return AjaxResult.success(categoryService.selectYjCategoryList(query));
    }

    /**
     * 获取参考文献
     * @return
     */
    @GetMapping(value = "getReferences")
    public AjaxResult getReferences() {
        YjReferences query = new YjReferences();
        query.setDataStatus("1");
        return AjaxResult.success(referencesService.selectYjReferencesList(query));
    }

    /**
     * 查询书籍列表
     * @return
     */
    @GetMapping(value = "getBooks")
    public AjaxResult getBooks() {
        YjBook query = new YjBook();
        query.setDataStatus("1");
        startPage();
        return AjaxResult.success(bookService.selectYjBookList(query));
    }

    /**
     * 获取数的章节列表
     * @param bookId
     * @return
     */
    @GetMapping(value = "getBookDetail/{bookId}")
    public AjaxResult getBookDetail(@PathVariable(value = "bookId", required = true) Long bookId) {
        YjBookChapter query = new YjBookChapter();
        query.setDataStatus("1");
        query.setBookId(bookId);
        return AjaxResult.success(chapterService.selectYjBookChapterList(query));
    }

    /**
     * 获取章节明细
     * @param chapterId
     * @return
     */
    @GetMapping(value = "getBookChapter/{chapterId}")
    public AjaxResult getBookChapter(@PathVariable(value = "chapterId", required = true) Long chapterId) {
        return AjaxResult.success(chapterService.selectYjBookChapterByChapterId(chapterId));
    }

    /**
     * 查询打赏商品列表
     * @return
     */
    @GetMapping(value = "getDaShangList")
    public AjaxResult getDaShangList() {
        YjDaShang query = new YjDaShang();
        query.setDataStatus("1");
        query.setType("gift");
        return AjaxResult.success(daShangService.selectYjDaShangList(query));
    }

    /**
     * 更新用户信息
     */
    @ApiOperation(value = "更新用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "customerName", value = "客户名称", paramType = "String", required = true),
            @ApiImplicitParam(name = "headImage", value = "头像", paramType = "String", required = true),
            @ApiImplicitParam(name = "sex", value = "性别", paramType = "String", required = true),
            @ApiImplicitParam(name = "nation", value = "国籍", paramType = "String", required = true),
            @ApiImplicitParam(name = "province", value = "省份", paramType = "String", required = true),
            @ApiImplicitParam(name = "city", value = "城市", paramType = "String", required = true),
    })
    @PostMapping("/updateCustomerInfo")
    public AjaxResult UpdateCustomerInfo(@RequestBody CustomerInfo customerInfo) {
        CustomerInfo ci =  getMemberInfo();
        if (ci == null){
            if (customerInfoService.insertCustomerInfo(customerInfo)>0){
                CustomerInfoAccount account =  getMemberAccount();
                if (account != null) {
                    account.setCustomerUid(customerInfo.getCustomerUid());
                    customerInfoAccountService.updateCustomerInfoAccount(account);
                }
                CustomerInfoAccountToken token = getMemberAccountToken();
                if (token != null){
                    token.setCustomerUid(customerInfo.getCustomerUid());
                    customerInfoAccountTokenService.updateCustomerInfoAccountToken(token);
                }
            }
        }else{
            ci.setCustomerName(customerInfo.getCustomerName());
            ci.setHeadImage(customerInfo.getHeadImage());
            ci.setSex(customerInfo.getSex());
            ci.setNation(customerInfo.getNation());
            ci.setProvince(customerInfo.getProvince());
            ci.setCity(customerInfo.getCity());
            customerInfoService.updateCustomerInfo(ci);
            CustomerInfoAccount account =  getMemberAccount();
            if (account != null && account.getCustomerUid() == null) {
                account.setCustomerUid(customerInfo.getCustomerUid());
                customerInfoAccountService.updateCustomerInfoAccount(account);
            }
            CustomerInfoAccountToken token = getMemberAccountToken();
            if (token != null && token.getCustomerUid() == null){
                token.setCustomerUid(customerInfo.getCustomerUid());
                customerInfoAccountTokenService.updateCustomerInfoAccountToken(token);
            }
        }
        //Object rst = customerInfoService.editCustomerInfo(customerInfo);
        return AjaxResult.success();
    }

    /**
     * 获取用信息
     * @return
     */
    @GetMapping(value = "getInfo")
    public AjaxResult getInfo() {
        Map<String,Object> rst = new HashMap<>();
        CustomerInfoAccountToken token = customerInfoAccountService.getToken(getMemberToken());
        if (token != null){
            rst.put("customerToken",token);
            CustomerInfoAccount account = customerInfoAccountService.selectCustomerInfoAccountByCustomerAccountUid(token.getCustomerAccountUid());
            if (account != null){
                rst.put("customerAccount",account);
            }
            if (token.getCustomerUid() != null) {
                CustomerInfo ci = customerInfoService.selectCustomerInfoByCustomerUid(token.getCustomerUid());
                if (ci != null) {
                    rst.put("customerInfo", ci);
                }
            }
        }
        return AjaxResult.success(rst);
    }
}
